import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse } from '@shared/types/market';

interface StockRanking {
  rank: number;
  code: string;
  name: string;
  current: number;
  change_pct: number;
  volume?: number;
  amount?: number;
}

interface RankingData {
  gainers: StockRanking[];
  losers: StockRanking[];
  turnover: StockRanking[];
}

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

const RankingList: React.FC = () => {
  // 获取排行榜数据
  const { data, isLoading, error } = useQuery({
    queryKey: ['stockRankings'],
    queryFn: async () => {
      const response = await get<ApiResponse<RankingData>>(
        `${API_BASE}/api/v1/market/stock-rankings?limit=10`
      );
      return response.data;
    },
    refetchInterval: 30000, // 30秒刷新
    staleTime: 15000,
  });

  const renderStockRow = (stock: StockRanking) => {
    // 安全地处理可能为undefined的数值
    const current = stock.current ?? 0;
    const changePct = stock.change_pct ?? 0;
    
    const isPositive = changePct >= 0;
    const changeColor = isPositive ? '#ef4444' : '#10b981';
    const bgColor = isPositive ? '#fee2e2' : '#d1fae5';

    return (
      <tr
        key={stock.code}
        className="hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0"
      >
        {/* 序号 */}
        <td className="px-3 py-3 text-center">
          <span
            className={`inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold ${
              stock.rank <= 3
                ? 'bg-gradient-to-br from-yellow-400 to-yellow-600 text-white'
                : 'bg-gray-200 text-gray-600'
            }`}
          >
            {stock.rank}
          </span>
        </td>

        {/* 代码 */}
        <td className="px-3 py-3">
          <div className="font-mono text-sm text-gray-700">{stock.code}</div>
        </td>

        {/* 名称 */}
        <td className="px-3 py-3">
          <div className="font-medium text-gray-900">{stock.name}</div>
        </td>

        {/* 价格 */}
        <td className="px-3 py-3 text-right">
          <div className="font-semibold text-gray-900">
            ¥{current.toFixed(2)}
          </div>
        </td>

        {/* 涨跌幅 */}
        <td className="px-3 py-3 text-right">
          <span
            className="inline-block px-2 py-1 rounded text-sm font-bold"
            style={{ color: changeColor, backgroundColor: bgColor }}
          >
            {isPositive ? '+' : ''}
            {changePct.toFixed(2)}%
          </span>
        </td>
      </tr>
    );
  };

  // 渲染单个排行榜表格
  const renderRankingTable = (
    stocks: StockRanking[],
    title: string,
    icon: string
  ) => {
    return (
      <div className="bg-white rounded-lg shadow-md p-6">
        <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
          <span>{icon}</span>
          <span>{title}</span>
        </h3>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 text-gray-600 text-sm">
                <th className="px-3 py-2 text-center w-12">序号</th>
                <th className="px-3 py-2 text-left">代码</th>
                <th className="px-3 py-2 text-left">名称</th>
                <th className="px-3 py-2 text-right">最新价</th>
                <th className="px-3 py-2 text-right">涨跌幅</th>
              </tr>
            </thead>
            <tbody>
              {stocks.length > 0 ? (
                stocks.map((stock) => renderStockRow(stock))
              ) : (
                <tr>
                  <td colSpan={5} className="text-center py-8 text-gray-400">
                    暂无数据
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        
        {/* 更新时间 */}
        <div className="mt-4 pt-3 border-t text-xs text-gray-400 text-center">
          最后更新: {new Date().toLocaleTimeString('zh-CN')}
        </div>
      </div>
    );
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {[1, 2].map((i) => (
          <div key={i} className="bg-white rounded-lg shadow-md p-6">
            <div className="h-6 bg-gray-200 rounded w-32 mb-4 animate-pulse"></div>
            <div className="space-y-3">
              {[1, 2, 3, 4, 5].map((j) => (
                <div key={j} className="h-12 bg-gray-100 rounded animate-pulse"></div>
              ))}
            </div>
          </div>
        ))}
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
        <div className="text-red-600 text-sm">
          <span className="text-lg">⚠️</span> 排行榜数据加载失败
        </div>
      </div>
    );
  }

  // 正常显示：涨幅榜和跌幅榜并排
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      {/* 涨幅榜 */}
      {renderRankingTable(data?.gainers || [], '涨幅榜', '📈')}
      
      {/* 跌幅榜 */}
      {renderRankingTable(data?.losers || [], '跌幅榜', '📉')}
    </div>
  );
};

export default RankingList;

